
<!DOCTYPE HTML>
<html lang="" >
    <head>
        <meta charset="UTF-8">
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>Controlled and uncontrolled inputs · React in patterns</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="GitBook 3.2.3">
        <meta name="author" content="Krasimir Tsonev">
        
        
    
    <link rel="stylesheet" href="../gitbook/style.css">

    
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-highlight/website.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-search/search.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-fontsettings/website.css">
                
            
        

    

    
        
        <link rel="stylesheet" href="../styles/website.css">
        
    
        
    
        
    

        
    
    
    <meta name="HandheldFriendly" content="true"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
    <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">

    
    <link rel="next" href="../chapter-06/" />
    
    
    <link rel="prev" href="../chapter-04/" />
    

    </head>
    <body>
        
<div class="book">
    <div class="book-summary">
        
            
<div id="book-search-input" role="search">
    <input type="text" placeholder="Type to search" />
</div>

            
                <nav role="navigation">
                


<ul class="summary">
    
    

    

    
        
        
    
        <li class="chapter " data-level="1.1" data-path="../">
            
                <a href="../">
            
                    
                    Introduction
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="../chapter-01/">
            
                <a href="../chapter-01/">
            
                    
                    In brief
            
                </a>
            

            
        </li>
    

    
        
        <li class="header">Foundation</li>
        
        
    
        <li class="chapter " data-level="2.1" data-path="../chapter-02/">
            
                <a href="../chapter-02/">
            
                    
                    Communication
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="2.1.1" data-path="../chapter-02/">
            
                <a href="../chapter-02/#input">
            
                    
                    Input
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="2.1.2" data-path="../chapter-02/">
            
                <a href="../chapter-02/#output">
            
                    
                    Output
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="2.2" data-path="../chapter-03/">
            
                <a href="../chapter-03/">
            
                    
                    Event handlers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="2.3" data-path="../chapter-04/">
            
                <a href="../chapter-04/">
            
                    
                    Composition
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="2.3.1" data-path="../chapter-04/">
            
                <a href="../chapter-04/#using-reacts-children-api">
            
                    
                    Using React's children API
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="2.3.2" data-path="../chapter-04/">
            
                <a href="../chapter-04/#passing-a-child-as-a-prop">
            
                    
                    Passing a child as a prop
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="2.3.3" data-path="../chapter-04/">
            
                <a href="../chapter-04/#higher-order-component">
            
                    
                    Higher-order component
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="2.3.4" data-path="../chapter-04/">
            
                <a href="../chapter-04/#function-as-a-children-render-prop">
            
                    
                    Function as a children, render prop
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter active" data-level="2.4" data-path="./">
            
                <a href="./">
            
                    
                    Controlled and uncontrolled inputs
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="2.5" data-path="../chapter-06/">
            
                <a href="../chapter-06/">
            
                    
                    Presentational and container components
            
                </a>
            

            
        </li>
    

    
        
        <li class="header">Data flow</li>
        
        
    
        <li class="chapter " data-level="3.1" data-path="../chapter-07/">
            
                <a href="../chapter-07/">
            
                    
                    One direction data flow
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="3.2" data-path="../chapter-08/">
            
                <a href="../chapter-08/">
            
                    
                    Flux
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="3.2.1" data-path="../chapter-08/">
            
                <a href="../chapter-08/#flux-architecture-and-its-main-characteristics">
            
                    
                    Flux architecture and its main characteristics
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="3.2.2" data-path="../chapter-08/">
            
                <a href="../chapter-08/#implementing-a-flux-architecture">
            
                    
                    Implementing a Flux architecture
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="3.3" data-path="../chapter-09/">
            
                <a href="../chapter-09/">
            
                    
                    Redux
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="3.3.1" data-path="../chapter-09/">
            
                <a href="../chapter-09/#redux-architecture-and-its-main-characteristics">
            
                    
                    Redux architecture and its main characteristics
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="3.3.2" data-path="../chapter-09/">
            
                <a href="../chapter-09/#simple-counter-app-using-redux">
            
                    
                    Simple counter app using Redux
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    

    
        
        <li class="header">Good to know</li>
        
        
    
        <li class="chapter " data-level="4.1" data-path="../chapter-10/">
            
                <a href="../chapter-10/">
            
                    
                    Dependency injection
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="4.1.1" data-path="../chapter-10/">
            
                <a href="../chapter-10/#using-reacts-context-prior-v-163">
            
                    
                    Using React's context (prior to v. 16.3)
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="4.1.2" data-path="../chapter-10/">
            
                <a href="../chapter-10/#using-reacts-context-v-163-and-above">
            
                    
                    Using React's context (v. 16.3 and above)
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="4.1.3" data-path="../chapter-10/">
            
                <a href="../chapter-10/#using-the-module-system">
            
                    
                    Using the module system
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="4.2" data-path="../chapter-11/">
            
                <a href="../chapter-11/">
            
                    
                    Styling
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="4.2.1" data-path="../chapter-11/">
            
                <a href="../chapter-11/#the-good-old-css-class">
            
                    
                    The good old CSS class
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="4.2.2" data-path="../chapter-11/">
            
                <a href="../chapter-11/#inline-styling">
            
                    
                    Inline styling
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="4.2.3" data-path="../chapter-11/">
            
                <a href="../chapter-11/#css-modules">
            
                    
                    CSS modules
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="4.2.4" data-path="../chapter-11/">
            
                <a href="../chapter-11/#styled-components">
            
                    
                    Styled-components
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="4.3" data-path="../chapter-12/">
            
                <a href="../chapter-12/">
            
                    
                    Integration of third-party libraries
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="4.4" data-path="../chapter-13/">
            
                <a href="../chapter-13/">
            
                    
                    React and separation of concerns
            
                </a>
            

            
        </li>
    

    
        
        <li class="header">Summary</li>
        
        
    
        <li class="chapter " data-level="5.1" data-path="../chapter-14/">
            
                <a href="../chapter-14/">
            
                    
                    Summary
            
                </a>
            

            
        </li>
    

    

    <li class="divider"></li>

    <li>
        <a href="https://www.gitbook.com" target="blank" class="gitbook-link">
            Published with GitBook
        </a>
    </li>
</ul>


                </nav>
            
        
    </div>

    <div class="book-body">
        
            <div class="body-inner">
                
                    

<div class="book-header" role="navigation">
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href=".." >Controlled and uncontrolled inputs</a>
    </h1>
</div>




                    <div class="page-wrapper" tabindex="-1" role="main">
                        <div class="page-inner">
                            
<div id="book-search-results">
    <div class="search-noresults">
    
                                <section class="normal markdown-section">
                                
                                <h1 id="controlled-and-uncontrolled-inputs">Controlled and uncontrolled inputs</h1>
<p>These two terms <em>controlled</em> and <em>uncontrolled</em> are very often used in the context of forms management. <em>controlled</em> input is an input that gets its value from a single source of truth. For example the <code>App</code> component below has a single <code>&lt;input&gt;</code> field which is <em>controlled</em>:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-keyword">super</span>(props);
    <span class="hljs-keyword">this</span>.state = { value: <span class="hljs-string">&apos;hello&apos;</span> };
  }
  render() {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&apos;text&apos;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{</span> <span class="hljs-attr">this.state.value</span> } /&gt;</span>;
  }
};
</span></code></pre>
<p>The result of this code is an input element that we can focus but can&apos;t change. It is never updated because we have a single source of truth - the <code>App</code>&apos;s component state. To make the input work as expected we have to add an <code>onChange</code> handler and update the state (the single source of truth). Which will trigger a new rendering cycle and we will see what we typed.</p>
<p><span class="new-page"></span></p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-keyword">super</span>(props);
    <span class="hljs-keyword">this</span>.state = { value: <span class="hljs-string">&apos;hello&apos;</span> };
    <span class="hljs-keyword">this</span>._change = <span class="hljs-keyword">this</span>._handleInputChange.bind(<span class="hljs-keyword">this</span>);
  }
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">&apos;text&apos;</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{</span> <span class="hljs-attr">this.state.value</span> }
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{</span> <span class="hljs-attr">this._change</span> } /&gt;</span>
    );
  }
  _handleInputChange(e) {
    this.setState({ value: e.target.value });
  }
};
</span></code></pre>
<p>On the opposite side is the <em>uncontrolled</em> input where we let the browser handle the user&apos;s updates. We may still provide an initial value by using the <code>defaultValue</code> prop but after that the browser is responsible for keeping the state of the input.</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-keyword">super</span>(props);
    <span class="hljs-keyword">this</span>.state = { value: <span class="hljs-string">&apos;hello&apos;</span> };
  }
  render() {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&apos;text&apos;</span> <span class="hljs-attr">defaultValue</span>=<span class="hljs-string">{</span> <span class="hljs-attr">this.state.value</span> } /&gt;</span>
  }
};
</span></code></pre>
<p>That <code>&lt;input&gt;</code> element above is a little bit useless because the user updates the value but our component has no idea about that. We then have to use <a href="https://reactjs.org/docs/glossary.html#refs" target="_blank"><code>Refs</code></a> to get access to the actual element.</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-keyword">super</span>(props);
    <span class="hljs-keyword">this</span>.state = { value: <span class="hljs-string">&apos;hello&apos;</span> };
    <span class="hljs-keyword">this</span>._change = <span class="hljs-keyword">this</span>._handleInputChange.bind(<span class="hljs-keyword">this</span>);
  }
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">&apos;text&apos;</span>
        <span class="hljs-attr">defaultValue</span>=<span class="hljs-string">{</span> <span class="hljs-attr">this.state.value</span> }
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{</span> <span class="hljs-attr">this._change</span> }
        <span class="hljs-attr">ref</span>=<span class="hljs-string">{</span> <span class="hljs-attr">input</span> =&gt;</span> this.input = input }/&gt;
    );
  }
  _handleInputChange() {
    this.setState({ value: this.input.value });
  }
};
</span></code></pre>
<p>The <code>ref</code> prop receives a string or a callback. The code above uses a callback and stores the DOM element into a <em>local</em> variable called <code>input</code>. Later when the <code>onChange</code> handler is fired we get the new value and send it to the <code>App</code>&apos;s state.</p>
<p><em>Using a lot of <code>refs</code> is not a good idea. If it happens in your app consider using <code>controlled</code> inputs and re-think your components.</em></p>
<h2 id="final-thoughts">Final thoughts</h2>
<p><em>controlled</em> versus <em>uncontrolled</em> inputs is very often underrated. However I believe that it is a fundamental decision because it dictates the data flow in the React component. I personally think that <em>uncontrolled</em> inputs are kind of an anti-pattern and I&apos;m trying to avoid them when possible.</p>

                                
                                </section>
                            
    </div>
    <div class="search-results">
        <div class="has-results">
            
            <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
            <ul class="search-results-list"></ul>
            
        </div>
        <div class="no-results">
            
            <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
            
        </div>
    </div>
</div>

                        </div>
                    </div>
                
            </div>

            
                
                <a href="../chapter-04/#function-as-a-children-render-prop" class="navigation navigation-prev " aria-label="Previous page: Function as a children, render prop">
                    <i class="fa fa-angle-left"></i>
                </a>
                
                
                <a href="../chapter-06/" class="navigation navigation-next " aria-label="Next page: Presentational and container components">
                    <i class="fa fa-angle-right"></i>
                </a>
                
            
        
    </div>

    <script>
        var gitbook = gitbook || [];
        gitbook.push(function() {
            gitbook.page.hasChanged({"page":{"title":"Controlled and uncontrolled inputs","level":"2.4","depth":1,"next":{"title":"Presentational and container components","level":"2.5","depth":1,"path":"chapter-06/README.md","ref":"chapter-06/README.md","articles":[]},"previous":{"title":"Function as a children, render prop","level":"2.3.4","depth":2,"anchor":"#function-as-a-children-render-prop","path":"chapter-04/README.md","ref":"chapter-04/README.md#function-as-a-children-render-prop","articles":[]},"dir":"ltr"},"config":{"plugins":[],"root":"./book","styles":{"website":"./styles/website.css","ebook":"./styles/ebook.css","pdf":"./styles/ebook.css"},"pluginsConfig":{"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"theme":"default","author":"Krasimir Tsonev","pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a5","chapterMark":"pagebreak","pageBreaksBefore":"//*[@class='new-page']","margin":{"right":62,"left":62,"top":56,"bottom":56}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"variables":{},"title":"React in patterns","gitbook":"3.2.3","description":"A book about common design patterns used while developing with React."},"file":{"path":"chapter-05/README.md","mtime":"2023-07-06T05:38:39.116Z","type":"markdown"},"gitbook":{"version":"3.2.3","time":"2025-01-27T05:24:55.061Z"},"basePath":"..","book":{"language":""}});
        });
    </script>
</div>

        
    <script src="../gitbook/gitbook.js"></script>
    <script src="../gitbook/theme.js"></script>
    
        
        <script src="../gitbook/gitbook-plugin-search/search-engine.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-sharing/buttons.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
        
    

    </body>
</html>

